// import type { JdSheet } from 'spread_sdk';
import { JdSheet } from "../types/spread";

/**
 * @typedef CellMetaOri
 * @property {string} tableName
 * @property {string} fieldName
 * @property {string} dataType
 */
/**
 * @typedef CellMeta
 * @property {string} tableName
 * @property {string} fieldName
 * @property {string} dataType
 * @property {string} sheet
 * @property {number} posRow
 * @property {number} posCol
 */

export function getInfoStr(...arr: (string | number)[]) {
    return arr.join("-");
}
export function getInfoArr(str: string) {
    return str.split("-");
}

export function flatSheetCells(data: JdSheet.ISourceData[string], sheetName: string) {
    const allCells: JdSheet.CellMeta[] = [];

    Object.keys(data).map((rowIdx) => {
        Object.keys(data[rowIdx]).map((colIdx) => {
            const cell = data[rowIdx][colIdx];
            cell.sheet = sheetName;
            cell.posRow = rowIdx;
            cell.posCol = colIdx;
            allCells.push(cell as JdSheet.CellMeta);
        });
    });

    return allCells;
}

export function flatAllCells(data: JdSheet.ISourceData, limSheetName?: string) {
    let sheetNames = Object.keys(data);
    if (limSheetName && data[limSheetName]) {
        sheetNames = [limSheetName];
    }

    const allCells: Record<string, JdSheet.CellMeta[]> = {};

    sheetNames.map((sheetName) => {
        allCells[sheetName] = flatSheetCells(data[sheetName], sheetName);
    });

    return allCells;
}

export function foreachSheetsCell<T>(data: JdSheet.ISheetCellInfo<T>, fn: (sheetName: string, rowIdx: number, colIdx: number) => void) {
    Object.keys(data).map((sheetName) => {
        const sheet = data[sheetName];
        Object.keys(sheet).map((rowIdx) => {
            const row = sheet[rowIdx];
            Object.keys(row).map((colIdx) => {
                fn(sheetName, parseInt(rowIdx), parseInt(colIdx));
            });
        });
    });
}

/**
 * 构建 pos 和 数据库表字段映射信息
 */
export function buildMapPos2TF(allCells: JdSheet.CellMeta[]) {
    const mapPos2Db: JdSheet.MapPos2db = {};
    const mapDb2Pos: JdSheet.MapDb2Pos = {};
    allCells.map((cell) => {
        const posStr = getInfoStr(cell.posRow, cell.posCol);
        const tfStr = getInfoStr(cell.tableName, cell.fieldName);

        if (mapPos2Db[tfStr]) {
            console.error();
        }

        mapPos2Db[posStr] = [cell.tableName, cell.fieldName];
        mapDb2Pos[tfStr] = [cell.posRow, cell.posCol];
    });
    return { mapPos2Db, mapDb2Pos };
}
